import time

from selenium import webdriver
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


class Base:
    """
    基础类,封装了selenium基础方法,供page包下面的类继承
    """

    def __init__(self, browser):
        # 打开浏览器, 设置driver
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None
        self.driver.implicitly_wait(8)

    def get(self, url):
        # 请求目标网址
        # selenium.common.exceptions.InvalidArgumentException: Message: invalid argument
        # selenium.common.exceptions.WebDriverException: Message: unknown
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('输入的地址不正确')

    def find_element(self, locator):  # locator = (By.xxx, value)
        # 定位元素
        try:
            return self.driver.find_element(*locator)  # *locator = By.xxx, value
        except NoSuchElementException:
            print('元素定位失败')

    def click(self, locator):
        # 元素点击操作
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('元素定位失败')

    # 获取元素属性
    def get_attribute(self, value, locator):
        # 定位元素
        element = self.find_element(locator)
        # 元素属性
        if element is not None:
            print(element.get_attribute(value))
        else:
            print('元素定位失败')

    def forward(self):
        # 前进
        self.driver.forward()

    def back(self):
        # 浏览器后退
        self.driver.back()

    def refresh(self):
        # 点击刷新
        self.driver.refresh()

    def quit(self, seconds=0):
        # 退出浏览器
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com')
    base.find_element(('id', 'kw'))
    base.click(('id', 'su'))
    base.forward()
    base.back()
    base.refresh()
    base.get_attribute('id', (By.NAME, 'wd'))
    base.quit()


